﻿using House.Common;
using House.DTO;
using House.IService;
using House.Service.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;

namespace House.Service
{
    public class AdminUserService : BaseService<T_AdminUsers>, IAdminUserService
    {
        public AdminUserService()
            : base(new Model())
        {

        }
        //删除
        public AjaxResult<bool> Delete(params long[] id)
        {
            try
            {
                if (id.Length < 1)
                {
                    return AjaxResult<bool>.Fail("请指定删除的id");
                }
                else if (id.Length == 1)
                {
                    var result = base.Delete(id[0]);
                    if (result)
                    {
                        return AjaxResult<bool>.Success(true);
                    }
                    return AjaxResult<bool>.Fail("删除的数据不存在");
                }
                else
                {
                    var arr = DB.T_AdminUsers.Where(p => id.Contains(p.Id));
                    //开始一个事务
                    var tran = DB.Database.BeginTransaction();
                    foreach (var item in arr)
                    {
                        item.IsDeleted = true;
                    }
                    var row = DB.SaveChanges();
                    if (arr.Count() == row)
                    {
                        tran.Commit();
                        return AjaxResult<bool>.Success(true);
                    }
                    else
                    {
                        tran.Rollback();
                        return AjaxResult<bool>.Fail("不允许部分删除");
                    }

                }

            }
            catch (Exception ex)
            {
                return AjaxResult<bool>.Fail(ex.Message);
            }
        }

        public AdminUserEditDTO GetEdit(long id)
        {
            var admin = Get(p => p.Id == id);
            if (admin == null)
                return null;

            return new AdminUserEditDTO()
            {
                Id = admin.Id,
                CityId = (long)admin.CityId,
                Email = admin.Email,
                Name = admin.Name,
                PhoneNum = admin.PhoneNum,
                RoleIds = admin.T_Roles.Select(p => p.Id).ToArray()
            };
        }


        //查询
        public List<AdminUserDTO> GetList(int start, int length, string name, ref long rowCount)
        {
            var list = GetPagedList(start, length, ref rowCount, p => p.Name.Contains(name), p => p.CreateDateTime, false);
            return list.Select(p => new AdminUserDTO()
            {
                Email = p.Email,
                Id = p.Id,
                Name = p.Name,
                PhoneNum = p.PhoneNum,
                CityId = p.CityId == null ? 0 : (long)p.CityId,
                CityName = p.T_Cities == null ? "" : p.T_Cities.Name,
                LoginErrorTimes = p.LoginErrorTimes
            }).ToList();

            //throw new NotImplementedException();
        }
        //添加
        public AjaxResult<bool> Insert(AdminUserAddDTO admin)
        {
            try
            {
                string salt = new Random().Next(1000, 9999).ToString();
                #region 另一种方法
                //var user = new T_AdminUsers()
                //{
                //    CityId = admin.CityId,
                //    Email = admin.Email,
                //    Name=admin.Name,
                //    PhoneNum = admin.PhoneNum,
                //    PasswordSalt = salt,
                //    //MD5加盐加密
                //    PasswordHash = CommonHelper.CalcMD5(admin.Password + salt),
                //    CreateDateTime = DateTime.Now,
                //    LastLoginErrorDateTime = null
                //};
                //var roles = DB.T_Roles.Where(p => admin.RoleIds.Contains(p.Id));
                //foreach (var role in roles)
                //{
                //    user.T_Roles.Add(role);
                //}
                //var result = AddBool(user);
                #endregion
                var result = AddBool(new T_AdminUsers()
                {
                    CityId = admin.CityId,
                    Email = admin.Email,
                    Name = admin.Name,
                    PhoneNum = admin.PhoneNum,
                    PasswordSalt = salt,
                    //MD5加盐加密
                    PasswordHash = CommonHelper.CalcMD5(admin.Password + salt),
                    CreateDateTime = DateTime.Now,
                    LastLoginErrorDateTime = null
                });
                if (result)
                {
                    return AjaxResult<bool>.Success(true);
                }
                else
                {
                    return AjaxResult<bool>.Fail("添加失败");
                }
            }
            catch (Exception ex)
            {
                return AjaxResult<bool>.Fail(ex.Message);
            }
        }
        //注册登录
        public AjaxResult<bool> Login(LoginDTO login)
        {
            var user = Get(p => p.PhoneNum == login.PhoneNum);
            if (user == null)
            {
                return AjaxResult<bool>.Fail("手机号尚未注册");
            }
            var salt = user.PasswordSalt;
            var pass = CommonHelper.CalcMD5(login.Password + salt);
            if (user.PasswordHash != pass)
            {
                return AjaxResult<bool>.Fail("密码不正确");
            }
            var admin = new LoginAdminDTO()
            {
                CityId = user.CityId == null ? 0 : (long)user.CityId,
                Id = user.Id,
                Name = user.Name,
                PhoneNum = user.PhoneNum,
                RoleName = user.T_Roles.FirstOrDefault().Name
            };
            //dto  =》json  =》票据 =>票据加密=》cookie
            //1、将LoginAdminDTO序列化，方便存入票据（Service也需要添加json引用，以及版本一致）
            var json = admin.ToJson();
            //2、创建票据FormsAuthenticationTicket
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, "loginUser", DateTime.Now, DateTime.Now.AddDays(1), false, json);
            //3、对票据加密FormsAuthentication.Encrypt(ticket)
            var encrypt = FormsAuthentication.Encrypt(ticket);
            //4、将加密后票据存入cookie（ HttpCookie ）
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypt);
            //5、若用户勾选记得我，则指定cookie有效期（ Expires ）
            if (login.IsRemeberMe)
            {
                cookie.Expires = DateTime.Now.AddDays(7);
            }
            //6、将cookie写入响应流中发送客户端（获取http请求上下文HttpContext ，移除原来的数据，存入新的）
            HttpContext context = HttpContext.Current;
            context.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
            context.Response.Cookies.Add(cookie);

            return AjaxResult<bool>.Success(true);
        }

        public AjaxResult<bool> Update(AdminUserEditDTO admin)
        {
            try
            {
                string salt = new Random().Next(1000, 9999).ToString();

                var user = Get(p => p.Id == admin.Id);
                user.Id = admin.Id;
                user.CityId = admin.CityId;
                user.Email = admin.Email;
                user.Name = admin.Name;
                user.PhoneNum = admin.PhoneNum;
                user.PasswordSalt = salt;
                user.PasswordHash = CommonHelper.CalcMD5(admin.Password + salt);

                user.T_Roles.Clear();

                var roles = DB.T_Roles.Where(p => admin.RoleIds.Contains(p.Id));
                foreach (var role in roles)
                {
                    user.T_Roles.Add(role);
                }

                var result = base.Update(user);
                if (result)
                {
                    return AjaxResult<bool>.Success(true);
                }
                return AjaxResult<bool>.Fail("修改失败");
            }
            catch (Exception ex)
            {
                return AjaxResult<bool>.Fail(ex.Message);
            }
        }
    }
}
